package com.xiaomaoguai.fcp.pre.kepler.delay.task.zk;

import com.xiaomaoguai.fcp.pre.kepler.delay.task.DelayTaskMsg;
import com.xiaomaoguai.fcp.pre.kepler.delay.task.DelayTaskProducer;
import com.xiaomaoguai.fcp.pre.kepler.delay.task.zk.config.DistributedDelayQueueFactory;
import org.apache.curator.framework.recipes.queue.DistributedDelayQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @fileName: ZkDelayTaskProducer.java
 * @author: WeiHui
 * @date: 2019/2/14 12:56
 * @version: v1.0.0
 * @since JDK 1.8
 */
@Service
public class ZkDelayTaskProducer implements DelayTaskProducer {

	/**
	 * logger
	 */
	private static final Logger log = LoggerFactory.getLogger(ZkDelayTaskProducer.class);

	@Override
	public void createDelayTask(String taskName, Object taskData, Long delaySeconds) {
		try {
			DelayTaskMsg delayTaskMsg = new DelayTaskMsg(taskName, taskData);
			delayTaskMsg.setDelaySeconds(delaySeconds);

			DistributedDelayQueue<DelayTaskMsg> distributedDelayQueue = DistributedDelayQueueFactory.getQueueMapping(taskName);
			distributedDelayQueue.put(delayTaskMsg, System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(delaySeconds));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("zk发送延迟任务失败", e);
		}
	}

}
